<html>
<head>
	<meta name="viewport" content="width=400px, initial-scale=.7, minimum-scale=.7" />
	<link rel="stylesheet" type="text/css" href="WW.css" />
	<title>Word Waffle - Game Over</title>

</head>
<body>
<?php
	mysql_connect("localhost", "root", "%Tg34fv1")or die("cannot connect"); 
	mysql_select_db("wordWaffle")or die("cannot select DB");
	$myKey = mysql_real_escape_string(stripslashes($_GET['sesskey']));
	$gameID = mysql_real_escape_string(stripslashes($_GET['gameID']));
	$w=mysql_query("SELECT * FROM waffle ORDER BY sesskey, x, y");
	//ensure there was a game being played
	$playerList=mysql_query("SELECT * FROM players ORDER BY sesskey");
	$playerCount = mysql_num_rows($playerList);
	if ($playerCount == 0)
	{
		echo "No game to score.";
		return;
	}	
	if (( $playerCount * 25) != mysql_num_rows($w))
	{
		echo "Game is not yet finished";
	 	return;
	}
	
	//display each waffle, wordlist, and total score
	$hiScore = 0;
	$hiScoreSess = $myKey;
	echo "<div id='tallies'>";
	for ($p=0;$p<$playerCount;$p++)
	{ //for each player
		
		echo "<div class='tally'>";
		$pn = mysql_fetch_assoc($playerList);
		echo "<h1>" . $pn['playerName'] . "</h1>";
		//display waffle
		echo "<div class='waffle'>";
		for ($k=1;$k<=5;$k++)
		{
			for ($j=1;$j<=5;$j++)
			{
				$l = mysql_fetch_assoc($w);
				echo "<div class='cell'>" . $l["letter"] . "</div>";
			}
			echo "<div style='clear:both'></div>";
		}
		echo "</div>"; //waffle
		
		//display wordlist and score
		$myScore = 0;
		$wl=mysql_query("SELECT * FROM allWords WHERE sesskey=" . $pn['sesskey']);
		echo "<div class='wordlist'>";
		while ($row = mysql_fetch_assoc($wl))
		{
			$mySess = $row['sesskey'];
			echo "<div class='word'>" . $row['word'] . "</div>";
			echo "<div class='value'>" . $row['value'] . "</div>";
			echo "<div style='clear:both'></div>";
			$myScore += $row['value'];
		}
		echo "<div class='score'>" . $myScore . "</div>";
		echo "</div>"; //wordlist
		echo "</div>"; //tally
		if ($myScore > $hiScore)
		{
			$hiScore = $myScore;
			$hiScoreSess = $mySess;
		}
	}
	echo "</div>";
	$winner = mysql_query("SELECT * FROM players WHERE sesskey=$hiScoreSess");
	$winnerRow = mysql_fetch_assoc($winner);
	
	//update end of game time & high score
	$result = mysql_query("SELECT * FROM gameStatus WHERE gameID=$gameID");
	if ($row = mysql_fetch_assoc($result))
	{
		if ($row['winnerID'] == 0)
		{
			$winnerID = $winnerRow['playerID'];
			$timestamp = date("Y-m-d H:i:s");
			mysql_query("UPDATE gameStatus SET endTime='$timestamp', winnerID=$winnerID, winningScore=$hiScore WHERE gameID=$gameID");
		}
	}
?>
<div id='winner'>WINNER IS: <?php echo $winnerRow['playerName'] . " with " . $hiScore; ?> points!!
<a class="letter" href="index.php?sesskey=<?php echo $myKey; ?>">Play again?</a>
<a class="letter" href="index.php">Return to menu</a>
</div>
</body>
</html>